class ListenScene extends Scene {

    private returnBtn: eui.Image;
    private eyeBtn: eui.ToggleButton;
    private listenMenuBtn: eui.Image;
    private introduceBtn: eui.Image;

    private showContentLabel: eui.Image;//点击屏幕显示释义

    private rollbackBtn: eui.Button;//回退
    private speedoffBtn: eui.Button;//快进
    private workBtn: eui.ToggleButton;//做题
    private cycleBtn: eui.ToggleButton;//单句循环
    private playBtn: eui.ToggleButton;//播放
    private progressSlider: eui.HSlider;//听力进度滚动条
    private currentTimeLabel: eui.Label;//音频播放到的时间
    private totalTimeLabel: eui.Label;//音频总时间
    private contentLayout: eui.Group;//听力原文部分
    private contentScroller: eui.Scroller;
    private content: eui.Group;

    private listeningID: number;
    private material: ListeningMaterial;
    private audioContext: wx.InnerAudioContext;
    private currentSentenceIndex = 0;
    private sentenceStartTime = -1;
    private sentenceEndTime = -1;
    private cycle = false;

    public constructor(listeningID?: number) {
        super();
        this.listeningID = listeningID;
    }

    public onSkinLoaded() {
        this.initListeners();
        this.initData();

        //添加听力原文的上下两个渐变
        let shp = new egret.Shape();
        let matrix = new egret.Matrix();
        matrix.createGradientBox(666, 150, Math.PI / 2, 43, 269);
        shp.graphics.beginGradientFill(egret.GradientType.LINEAR, [0xffffff, 0xffffff], [1, 0], [0, 255], matrix);
        shp.graphics.drawRect(43, 269, 666, 150);
        shp.graphics.endFill();
        matrix.createGradientBox(666, 150, Math.PI / 2, 43, 916);
        shp.graphics.beginGradientFill(egret.GradientType.LINEAR, [0xffffff, 0xffffff,], [0, 1], [0, 255], matrix);
        shp.graphics.drawRect(43, 916, 666, 150);
        shp.graphics.endFill();
        this.addChild(shp);
    }

    private initListeners() {
        this.returnBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.eyeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.listenMenuBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.introduceBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        //this.startBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);

        this.rollbackBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.speedoffBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.workBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.cycleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.btnHandler, this);
        this.playBtn.addEventListener(egret.TouchEvent.CHANGE, this.btnHandler, this);
    }

    private initData() {
        wx.request({
            url: Constants.HTTP_SERVER_URL + "/listening/getOne?id=" + this.listeningID,
            method: "GET",
            success: (res) => {
                if (res.statusCode == 200) {
                    console.log(res.data);
                    this.material = new ListeningMaterial(<{}>res.data);
                    this.initContentScroller();
                    this.updateContentScroller();
                    this.audioContext = wx.createInnerAudioContext();
                    this.audioContext.src = Constants.HTTP_SERVER_URL + "/resource/" + this.material.filePath;
                    this.progressSlider.minimum = 0;
                    this.progressSlider.maximum = this.material.soundTime * 100;
                    this.totalTimeLabel.text = this.formatTime(this.material.soundTime);
                    this.audioContext.onSeeked(() => {
                        let currentTime = this.audioContext.currentTime;
                        this.progressSlider.value = currentTime * 100;
                        this.clearContentScrollerColor();
                        this.currentSentenceIndex = 0;
                        for (let breakTime of this.material.sentenceBreakTimes) {
                            if (currentTime > breakTime) {
                                this.currentSentenceIndex++;
                            }
                            else break;
                        }
                        console.log("currentSentenceIndex:" + this.currentSentenceIndex)
                        this.updateContentScroller();
                        this.currentTimeLabel.text = this.formatTime(Math.floor(currentTime));
                    });
                    this.audioContext.onTimeUpdate(() => {
                        console.log("currentSentenceIndex:" + this.currentSentenceIndex)
                        let currentTime = this.audioContext.currentTime;
                        if (this.cycle) {
                            if (currentTime <= this.sentenceStartTime) {
                                this.audioContext.seek(this.sentenceStartTime);
                            } else if (currentTime >= this.sentenceEndTime || this.audioContext.paused) {
                                this.audioContext.play();
                                this.audioContext.seek(this.sentenceStartTime);
                            }
                        }
                        this.progressSlider.value = currentTime * 100;
                        if (currentTime > this.material.sentenceBreakTimes[this.currentSentenceIndex]) {
                            this.clearContentScrollerColor();
                            this.currentSentenceIndex++;
                            this.updateContentScroller();
                        }
                        this.currentTimeLabel.text = this.formatTime(Math.floor(currentTime));
                    });
                    this.progressSlider.addEventListener(eui.UIEvent.CHANGE, (event) => {
                        this.audioContext.seek(this.progressSlider.value / 100);
                    }, this);
                    this.audioContext.onEnded(() => {
                        if (!this.cycle) {
                            SceneManager.instance.addScene(new Listen2Scene(this.listeningID));
                            SceneManager.instance.removeScene(this);
                        }
                    });
                    console.log(this.material);
                } else {
                    console.log("statusCode:" + res.statusCode);
                }
            },
            fail: (err) => {
                console.log(err);
            }
        });
    }

    private initContentScroller() {
        for (let i = 0; i < this.material.sentenceCount; i++) {
            let sentence = this.material.content[i];
            let translation = this.material.translation[i];
            let group = new eui.Group();
            let vLayout = new eui.VerticalLayout();
            vLayout.gap = 24;
            group.layout = vLayout;
            let sentenceLabel = new eui.Label(sentence);
            sentenceLabel.textColor = 0x0c2f59;
            sentenceLabel.wordWrap = true;
            sentenceLabel.size = 32;
            sentenceLabel.width = 666;
            group.addChild(sentenceLabel);

            let translationLabel = new eui.Label(translation);
            translationLabel.textColor = 0x0c2f59;
            translationLabel.size = 28;
            translationLabel.width = 666;
            group.addChild(translationLabel);

            this.content.addChild(group);
        }
    }

    //清除当前currentSentenceIndex对应原文的颜色
    private clearContentScrollerColor() {
        let group = <eui.Group>this.content.getChildAt(this.currentSentenceIndex);
        let sentenceLabel = <eui.Label>group.getChildAt(0);
        sentenceLabel.textColor = 0x0c2f59;
    }

    //更新当前ContentScroller的位置及当前原文的颜色
    private updateContentScroller() {
        let tw = egret.Tween.get(this.contentScroller.viewport);
        let toY = this.content.getChildAt(this.currentSentenceIndex).y - 150;
        let group = <eui.Group>this.content.getChildAt(this.currentSentenceIndex);
        let sentenceLabel = <eui.Label>group.getChildAt(0);
        sentenceLabel.textColor = 0x6eccee;
        tw.to({ scrollV: toY }, 200);
    }

    private btnHandler(evt: egret.TouchEvent) {
        let btnFocused = evt.currentTarget;
        switch (btnFocused) {
            case this.returnBtn:
                if (this.audioContext != undefined)
                    this.audioContext.destroy();
                SceneManager.instance.removeScene(this);
                break;
            case this.eyeBtn:
                this.showContentLabel.visible = !this.eyeBtn.selected;
                this.contentLayout.visible = this.eyeBtn.selected;
                break;
            case this.workBtn:
                if (this.workBtn.selected) {
                    SceneManager.instance.addScene(new Listen2Scene(this.listeningID));
                }
                break;
            case this.cycleBtn:
                if (this.cycleBtn.selected) {
                    this.cycle = true;
                    this.progressSlider.enabled = false;
                    if (this.currentSentenceIndex == 0) {
                        this.sentenceStartTime = 0;
                    } else {
                        this.sentenceStartTime = this.material.sentenceBreakTimes[this.currentSentenceIndex - 1];
                    }

                    if (this.currentSentenceIndex == this.material.sentenceCount - 1) {
                        this.sentenceEndTime = this.material.soundTime;
                    } else {
                        this.sentenceEndTime = this.material.sentenceBreakTimes[this.currentSentenceIndex];
                    }
                } else {
                    this.cycle = false;
                    this.progressSlider.enabled = true;
                }
                break;
            case this.playBtn:
                if (this.playBtn.selected) {
                    this.audioContext.play();
                } else {
                    this.audioContext.pause();
                }
                break;
            case this.rollbackBtn:
                this.audioContext.seek(this.material.sentenceBreakTimes[this.currentSentenceIndex - 2]);
                break;
            case this.speedoffBtn:
                this.audioContext.seek(this.material.sentenceBreakTimes[this.currentSentenceIndex]);
                break;
        }
    }


    public formatTime(totalSeconds: number): string {
        let seconds = totalSeconds % 60;
        let minutes = (totalSeconds - seconds) / 60;
        return "0" + minutes + ":" + (seconds < 10 ? "0" + seconds : seconds);
    }
}